import { useState, useEffect, useRef, useMemo } from 'react'
import { Button, Input, Space, Empty } from 'antd'
import {
  BarsOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  CloseOutlined,
  DatabaseOutlined,
  EyeOutlined,
  MessageOutlined,
  ApiOutlined
} from '@ant-design/icons'
import PropTypes from 'prop-types'
import CommonTable from '../common/CommonTable'
import CommonForm from '../common/CommonForm'
import CommonModal from '../common/CommonModal'
import { generateRandomNumber } from '../../utils'


const InputMultipleComplex = ({
  value = [],
  onChange,
  onInnerChange,
  title = "",
  schema = [],
  createNewItem,
  width = 960,
  formWidth = 360,
  formProps = {},
  icon,
  setter,
  getter
}) => {
  const formRef = useRef(null)

  const [visible, setVisible] = useState(false)
  const [curId, setCurId] = useState(null)
  const [arr, setArr] = useState([])
  // const [valueInited, setValueInited] = useState(false)

  useEffect(() => {
    let _value
    if (value) {
      if (getter) {
        _value = getter(value)
      } else {
        _value = value
      }
      if (_value && _value.length > 0) {
        setArr(_value)
        setCurId(_value[0].$$hashKey)
      }else{
        setArr([])
      }
    } else {
      setArr([])
    }
  }, [value])

  useEffect(() => {
    if (formRef.current) {
      if (curId) {
        const _item = arr.find(el => el.$$hashKey === curId)
        formRef.current.setFieldsValue(_item)
      } else {
        // 清空需要把key全加上
        const emptyValues = {}
        for (let item of schema) {
          emptyValues[item.name] = undefined
        }
        formRef.current.setFieldsValue(emptyValues)
      }
    }
  }, [curId])

  const handleShow = () => {
    setVisible(true)
  }

  const handleCancel = () => {
    setVisible(false)
  }

  const handleConfirm = () => {
    handleCancel()
    if (setter) {
      onChange(setter(arr))
    } else {
      onChange(arr)
    }
  }

  const handleCreate = () => {
    let newItem = {
      $$hashKey: 'uiGrid-' + generateRandomNumber(4)
    }
    for (let item of schema) {
      newItem[item.name] = undefined
    }
    if (createNewItem) {
      const newData = createNewItem(arr)
      newItem = {
        ...newItem,
        ...newData
      }
    }
    setArr(arr.concat([newItem]))
    setCurId(newItem.$$hashKey)
  }

  const handleModify = (values) => {
    setArr(arr.map(el => {
      if (el.$$hashKey === curId) {
        return {
          ...el,
          ...values
        }
      } else {
        return el
      }
    }))
    onInnerChange && onInnerChange(curId, values, setArr)
  }

  const handleDelete = (index) => {
    if (arr[index].$$hashKey === curId) {
      setCurId(null)
    }
    setArr(arr.filter((el, i) => i !== index))
  }

  const handleUp = (index) => {
    setArr(arr.map((el, i) => {
      if (i === index) {
        return arr[index - 1]
      } else if (i === index - 1) {
        return arr[index]
      } else {
        return el
      }
    }))
  }

  const handleDown = (index) => {
    setArr(arr.map((el, i) => {
      if (i === index) {
        return arr[index + 1]
      } else if (i === index + 1) {
        return arr[index]
      } else {
        return el
      }
    }))
  }

  const getColumns = () => {
    const columns = schema.filter(el => !!el.tableColumn).map(el => {
      return {
        key: el.name,
        dataIndex: el.name,
        title: el.label,
        ...el.tableColumn
      }
    })
    return columns.concat([
      {
        key: 'action',
        title: '操作',
        width: 130,
        align: 'center',
        render: (text, rowData, index) => {
          return <Space>
            <Button
              size="small"
              disabled={index === 0}
              onClick={(e) => {
                e.stopPropagation()
                handleUp(index)
              }}
            >
              <ArrowUpOutlined />
            </Button>
            <Button
              size="small"
              disabled={index === arr.length - 1}
              onClick={(e) => {
                e.stopPropagation()
                handleDown(index)
              }}
            >
              <ArrowDownOutlined />
            </Button>
            <Button
              type="danger"
              size="small"
              onClick={(e) => {
                e.stopPropagation()
                handleDelete(index)
              }}
            >
              <CloseOutlined />
            </Button>
          </Space>
        }
      }
    ])
  }

  // const columns = useMemo(getColumns, [schema])
  const columns = getColumns()

  const renderIcon = () => {
    switch (icon) {
      case 'data':
        return <DatabaseOutlined />
      case 'eye':
        return <EyeOutlined />
      case 'up':
        return <ArrowUpOutlined />
      case 'message':
        return <MessageOutlined />
      case 'signal':
        return <ApiOutlined />
      default:
        return <BarsOutlined />
    }
  }

  const inputValue = useMemo(() => {
    let _value = []
    if (getter) {
      _value = getter(value) || []
    } else {
      _value = value || []
    }
    return _value.length ? `${_value.length} ${title || ''}` : ''
  }, [value])

  return <>
    <Input
      onClick={handleShow}
      readOnly
      value={inputValue}
      addonBefore={renderIcon()}
    />
    <CommonModal
      width={width}
      title={title}
      visible={visible}
      onCancel={handleCancel}
      onOk={handleConfirm}
      header={<div style={{ marginBottom: 10 }}><Button type="primary" onClick={handleCreate}>新增一条</Button></div>}
    >
      <div style={{
        height: 500,
        display: 'flex'
      }}>
        <div style={{
          height: '100%',
          overflow: 'auto',
          flex: 1
        }}>
          <CommonTable
            rowKey="$$hashKey"
            columns={columns}
            dataSource={arr}
            pagination={false}
            rowSelection={{
              type: 'radio',
              selectedRowKeys: [curId],
              onChange: (selectRowKeys) => {
                if (selectRowKeys.length > 0) {
                  setCurId(selectRowKeys[0])
                }
              }
            }}
            onRow={(rowData) => ({
              onClick: () => {
                setCurId(rowData.$$hashKey)
              }
            })}
          ></CommonTable>
        </div>
        <div style={{
          height: '100%',
          overflow: 'auto',
          marginLeft: 10,
          width: formWidth
        }}>
          {
            curId ?
              <CommonForm
                ref={formRef}
                formItems={schema}
                onValuesChange={handleModify}
                {...formProps}
              ></CommonForm> :
              <Empty description="请先选中一条数据"></Empty>
          }
        </div>
      </div>
    </CommonModal>
  </>
}

InputMultipleComplex.propTypes = {
  title: PropTypes.string,
  value: PropTypes.any,
  schema: PropTypes.array.isRequired,
  createNewItem: PropTypes.func,
  onChange: PropTypes.func,
  width: PropTypes.number,
  formWidth: PropTypes.number,
  formProps: PropTypes.object,
  icon: PropTypes.string,
  setter: PropTypes.func,
  getter: PropTypes.func
}

InputMultipleComplex.propsMap = []

export default InputMultipleComplex